﻿namespace SolidMvvm {
	using System;
	using System.Diagnostics;
	using System.IO;

	public class LoggerUncompressed : LoggerBase {
		public LoggerUncompressed(string filePathWithFileExtension) : base(filePathWithFileExtension) {
			try {
				AddMessage("Log initialized.", null);
			}
			catch (Exception exception) {
				Cleaner.CleanConstructor(this, exception);
			}
		}

		string Path => GetLogFilePath(DateTime.UtcNow);

		public override void Dispose() {
			using (var cleaner = new Cleaner()) {
				cleaner.CleanWithLambda(() => {
					if (!string.IsNullOrEmpty(FilePathWithFileExtension))
						AddMessage("Log finalized.", null);
				});

				cleaner.CleanWithLambda(() => base.Dispose());
			}
		}

		public override string GetLogFileAsString() {
			try {
				return File.ReadAllText(Path);
			}
			catch (Exception exception) {
				Debug.WriteLine("Error reading from log:\n\n" + exception);
				return string.Empty;
			}
		}

		public override void AddMessage(string publicMessage, string privateMessageOrNull) {
			try {
				var dateTimeStamp = DateTime.Now.ToString("O");

				// Write log entry as comma-delimited.
				var logMessage = dateTimeStamp + ", \"" + GetCSVedString(publicMessage) + "\", \"" + (privateMessageOrNull == null ? string.Empty : GetCSVedString(privateMessageOrNull)) + "\"";

				File.AppendAllText(Path, logMessage + Environment.NewLine);
			}
			catch (Exception exception) {
				Debug.WriteLine("Error writing to log:\n\n" + exception);
			}
		}
	}
}
